<template>
  <div class="app-container">
    <el-form ref="filterForm" :inline="true" :model="listQuery" class="filter-container">
      <el-form-item prop="sendtime">
        <el-date-picker
          v-model="listQuery.sendtime"
          type="date"
          size="small"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="listQuery.name" size="small" placeholder="推文标题" clearable style="width: 200px;" @keyup.enter.native="handleFilter" />
      </el-form-item>

      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleFilter">筛选</el-button>
        <el-button size="small" @click="resetFilter">重置</el-button>
        <el-button
          size="small"
          type="success"
          icon="el-icon-plus"
          @click="toTweetNew"
        >新建推送任务</el-button>
        <el-divider direction="vertical" />
        <el-button
          size="small"
          icon="el-icon-download"
          :loading="getTweetsDataLoading"
          :disabled="getTweetsDataLoading"
          @click="getTweetsData"
        >获取图文群发数据</el-button>
        <el-button
          size="small"
          icon="el-icon-download"
          :loading="exportTweetDetailsLoading"
          :disabled="exportTweetDetailsLoading"
          @click="exportTweetDetails"
        >推送任务明细导出</el-button>
      </el-form-item>
    </el-form>

    <el-card v-if="latelyList.length > 0" class="box-card mb30">
      <div slot="header" class="card-header clearfix">
        <h5 class="title pull-left">最近任务</h5>
        <el-button
          type="text"
          size="small"
          icon="el-icon-finished"
          class="btn pull-right"
          :loading="repeatBtnLoading"
          :disabled="repeatBtnLoading"
          @click="checkTaskOpenid"
        >校验用户是否重复</el-button>
      </div>
      <div class="card-wrapper text-center">
        <el-row v-for="(group, idx) in latelyGroup" :key="idx" :gutter="20">
          <el-col
            v-for="item in group"
            :key="item.id"
            :span="6"
            class="mb20"
          >
            <div v-if="item.materials.length > 0" class="media-card">
              <div
                v-for="(media, index) in item.materials"
                :key="media.id"
                class="media-item"
                :class="index === 0 ? 'first' : ''"
              >
                <div class="item-title">
                  <router-link :to="`/materials/list/${media.id}`">{{ media.title }}</router-link>
                </div>
                <div class="item-cover">
                  <img :src="media.cover" :alt="media.title" class="cover-img">
                  <div v-if="index === 0" class="cover-mask" />
                </div>
              </div>
            </div>
            <div class="task-name">
              <router-link :to="`/tweets/edit/${item.id}`">{{ item.name }}</router-link>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      stripe
      fit
      highlight-current-row
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <div v-if="!_.isEmpty(scope.row.depar)" class="table-expand-row">
            目标科室：
            <el-tag
              v-for="item in scope.row.depar"
              :key="item.id"
              effect="plain"
              size="small"
            >{{ item.name }}</el-tag>
          </div>
          <div v-if="!_.isEmpty(scope.row.brand)" class="table-expand-row">
            相关产品：
            <el-tag
              v-for="item in scope.row.brand"
              :key="item.id"
              type="success"
              effect="plain"
              size="small"
            >{{ item.brand }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="ID" width="80">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="标题">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="任务类型" width="120" align="center">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.tasktype === 0"
            effect="plain"
            type="success"
            size="mini"
          >普通任务</el-tag>
          <el-tag
            v-if="scope.row.tasktype === 1"
            effect="plain"
            size="mini"
          >定时任务</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="计划时间" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.plantime | moment('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column label="已推送" width="80" align="center">
        <template slot-scope="scope">
          <i v-if="scope.row.state === 1" class="el-icon-check text-success" />
          <i v-if="scope.row.state === 0" class="el-icon-close text-warning" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state === 0"
            size="mini"
            @click="toTweetEdit(scope.row.id)"
          >编辑任务</el-button>
          <el-popover
            v-if="scope.row.state === 1"
            width="300"
            trigger="click"
          >
            <el-row :gutter="10">
              <el-col :span="16">
                <el-date-picker
                  v-model="exportDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  size="small"
                  style="width: 100%;"
                />
              </el-col>
              <el-col :span="8">
                <el-button
                  icon="el-icon-download"
                  size="small"
                  plain
                  style="width: 100%;"
                  :disabled="exportTaskDataLoading"
                  @click="exportTaskData(scope.row.plantime)"
                >导出</el-button>
              </el-col>
            </el-row>

            <el-button
              slot="reference"
              type="success"
              size="mini"
              plain
              :loading="exportTaskDataLoading"
            >数据导出</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="fetchData" />

    <el-dialog
      title="文件正在生成中，请稍后到此链接下载文件"
      :visible.sync="showExportTweetDetailsLink"
      width="40%"
      center
    >
      <p class="text-center">{{ exportTweetDetailsLink }}</p>
      <div class="text-center mt30">
        <el-button
          type="success"
          plain
          @click="exportTweetDetailsLinkCopy(exportTweetDetailsLink, $event)"
        >复制下载地址</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="以下用户有重复，OpenId为："
      :visible.sync="repeatOpenid"
      width="50%"
      center
    >
      <el-table
        :data="repeatOpenidList"
        stripe
        fit
        highlight-current-row
      >
        <!-- <el-table-column label="任务名称">
          <template slot-scope="scope">
            {{ scope.row.taskName }}
          </template>
        </el-table-column> -->
        <el-table-column label="姓名">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="OpenId">
          <template slot-scope="scope">
            {{ scope.row.openid }}
          </template>
        </el-table-column>
        <el-table-column label="科室" width="160" align="center">
          <template slot-scope="scope">
            {{ scope.row.depart }}
          </template>
        </el-table-column>
      </el-table>
      <div class="text-warning text-center mt40">请在任务中找到该用户，进行移除操作</div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTweetsList,
  checkAllTaskOpenid
} from '@/api/tweets'
import {
  getTweetsData,
  exportTaskData,
  exportTweetDetails
} from '@/api/statements'
import Pagination from '@/components/Pagination'
import {
  blobExport,
  formatQuery
} from '@/utils'
import clip from '@/utils/clipboard'

export default {
  name: 'TweetsList',
  components: {
    Pagination
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      list: null,
      listLoading: true,
      total: 0,
      listQuery: {
        sendtime: formatQuery(this.$route.query.sendtime, false),
        name: formatQuery(this.$route.query.name, false),
        page: 1,
        size: 30
      },
      latelyList: [],
      latelyGroup: [],
      repeatOpenid: false,
      repeatBtnLoading: false,
      repeatOpenidList: [],
      exportDate: '',
      getTweetsDataLoading: false,
      exportTaskDataLoading: false,
      exportTweetDetailsLoading: false,
      showExportTweetDetailsLink: false,
      exportTweetDetailsLink: ''
    }
  },
  // watch: {
  //   $route: {
  //     handler(route) {
  //       if (!this._.isNil(route.query.page) &&
  //         !this._.isEmpty(route.query.page)
  //       ) {
  //         this.listQuery.page = parseInt(route.query.page)
  //       } else {
  //         this.listQuery.page = 1
  //       }
  //     },
  //     immediate: true
  //   }
  // },
  created() {
    if (!this._.isNil(this.$route.query.page) &&
      !this._.isEmpty(this.$route.query.page)
    ) {
      this.listQuery.page = parseInt(this.$route.query.page)
    } else {
      this.listQuery.page = 1
    }
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const query = {
        ...this.$route.query,
        ...this.listQuery
      }
      this.$router.push({
        query
      }).catch(err => {
        console.log(err)
      })
      getTweetsList(this.listQuery).then(response => {
        // console.log(response)
        const { data } = response
        // console.log(data)
        if (!this._.isEmpty(data)) {
          this.list = data.list
          this.latelyList = data.lately
          this.latelyGroup = this._.chunk(data.lately, 4)
        } else {
          this.list = []
          this.latelyList = []
          this.latelyGroup = []
        }
        this.total = response.total
        this.listLoading = false
        // console.log(this.latelyGroup)
      }).catch(err => {
        console.log(err)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.list = []
      this.fetchData()
    },
    resetFilter() {
      this.$refs.filterForm.resetFields()
      for (const i in this.listQuery) {
        if (i !== 'size') {
          this.listQuery[i] = undefined
        }
      }
      // console.log(this.listQuery)
      this.$router.push({
        query: {
          page: 1
        }
      }).catch(err => {
        console.log(err)
      })
      this.handleFilter()
    },
    getTweetsData() {
      if (this._.isEmpty(this.listQuery.sendtime)) {
        this.$message({
          type: 'warning',
          message: '请选择发送日期！'
        })
      } else {
        this.getTweetsDataLoading = true
        getTweetsData({
          sendDate: this.listQuery.sendtime
        }).then(response => {
          // console.log(response)
          this.$message({
            type: 'success',
            message: response.msg,
            duration: 5000
          })
          this.getTweetsDataLoading = false
        }).catch(err => {
          console.log(err)
          this.getTweetsDataLoading = false
        })
      }
    },
    exportTaskData(date) {
      const sendDate = this.$moment(date).format('YYYY-MM-DD')
      // console.log(sendDate)
      if (this._.isEmpty(this.exportDate)) {
        this.$message({
          type: 'warning',
          message: '请选择导出日期！'
        })
      } else {
        this.exportTaskDataLoading = true
        exportTaskData({
          sendDate,
          nowDate: this.exportDate
        }).then(response => {
          // console.log(response)
          blobExport(response, `微信图文数据 ${this.exportDate}.xlsx`)

          this.$message({
            type: 'success',
            message: '导出成功！',
            duration: 5000
          })
          this.exportDate = ''
          this.exportTaskDataLoading = false
        }).catch(err => {
          console.log(err)
          this.exportTaskDataLoading = false
        })
      }
    },
    exportTweetDetails() {
      // console.log(sendDate)
      if (this._.isEmpty(this.listQuery.sendtime)) {
        this.$message({
          type: 'warning',
          message: '请选择发送日期！'
        })
      } else {
        this.exportTweetDetailsLoading = true
        exportTweetDetails({
          sendDate: this.listQuery.sendtime
        }).then(response => {
          // console.log(response)
          // blobExport(response, `推送任务明细 ${this.listQuery.sendtime}.xlsx`)

          this.exportTweetDetailsLink = response.msg
          this.showExportTweetDetailsLink = true
          this.exportTweetDetailsLoading = false
        }).catch(err => {
          console.log(err)
          this.exportTweetDetailsLoading = false
        })
      }
    },
    exportTweetDetailsLinkCopy(text, event) {
      clip(text, event)
    },
    toTweetNew() {
      this.$router.push('/tweets/new')
    },
    toTweetEdit(id) {
      this.$router.push(`/tweets/edit/${id}`)
    },
    checkTaskOpenid() {
      this.repeatBtnLoading = true
      const taskIds = this._.map(this.latelyList, 'id').join(',')
      checkAllTaskOpenid({
        taskids: taskIds
      }).then(response => {
        // console.log(response)
        const { data } = response
        if (!this._.isEmpty(data.repeatOpenid)) {
          this.repeatOpenidList = data.repeatOpenid
          this.repeatOpenid = true
        } else {
          this.$message({
            type: 'info',
            message: '暂无重复用户'
          })
        }
        this.repeatBtnLoading = false
      }).catch(err => {
        console.log(err)
        this.repeatBtnLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.card-wrapper {
  .task-name {
    width: 300px;
    line-height: 1.5;
    margin: 0 auto;
    word-break: break-all;
  }
}
</style>
